package com.example.demo.controller;

import com.example.demo.common.BaseResponse;
import com.example.demo.common.ErrorCode;
import com.example.demo.common.ResultUtils;
import com.example.demo.exception.BusinessException;
import com.example.demo.entity.CopyrightTransferEntity;
import com.example.demo.model.CopyrightInfo;
import com.example.demo.model.CopyrightTransferInfo;
import com.example.demo.service.CopyrightService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * 版权控制器
 */
@RestController
@RequestMapping("/api/copyright")
@CrossOrigin(origins = "*")
public class CopyrightController {

    private static final Logger log = LoggerFactory.getLogger(CopyrightController.class);

    @Autowired
    private CopyrightService copyrightService;

    /**
     * 创建存证记录
     * @param address 所有者ID
     * @param imageName 作品名称 (可选)
     * @param modelName 模型名称 (可选)
     * @param prompt 提示词 (可选)
     * @param file 图片文件
     * @return 存证记录
     */
    @PostMapping("/certificate")
    public BaseResponse<CopyrightInfo> createCertificate(
            @RequestParam String address,
            @RequestParam(required = false) String imageName,
            @RequestParam(required = false) String modelName,
            @RequestParam(required = false) String prompt,
            @RequestParam("file") MultipartFile file) {
        if (address == null || address.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "所有者地址不能为空");
        }
        if (file == null || file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
        
        try {
            // 调用服务层处理业务逻辑
            CopyrightInfo newCertificate = copyrightService.createCertificateAndGetInfo(
                    address, imageName, modelName, prompt, file);
            return ResultUtils.success(newCertificate);
        } catch (Exception e) {
            log.error("创建存证记录失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建存证记录失败：" + e.getMessage());
        }
    }

    /**
     * 转让版权
     * @param fromAddress 当前所有者地址
     * @param blockchainId 区块链ID
     * @param toAddress 接收者地址
     * @return 更新后的版权信息
     */
    @PostMapping("/transfer")
    public BaseResponse<CopyrightInfo> transferCopyright(
            @RequestParam String fromAddress,
            @RequestParam String blockchainId,
            @RequestParam String toAddress) {
        if (fromAddress == null || fromAddress.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "所有者地址不能为空");
        }
        if (toAddress == null || toAddress.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接收者地址不能为空");
        }
        if (blockchainId == null || blockchainId.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "版权ID不能为空");
        }
        
        try {
            CopyrightInfo result = copyrightService.transferCopyright(blockchainId, fromAddress, toAddress);
            return ResultUtils.success(result);
        } catch (IllegalArgumentException e) {
            log.warn("版权转让参数校验失败: {}", e.getMessage());
            throw new BusinessException(ErrorCode.PARAMS_ERROR, e.getMessage());
        } catch (Exception e) {
            log.error("版权转让失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "版权转让失败: " + e.getMessage());
        }
    }

    /**
     * 获取版权信息
     * @param copyrightId 版权ID
     * @return 版权信息
     */
    @GetMapping("/{copyrightId}")
    public BaseResponse<CopyrightInfo> getCopyright(@PathVariable BigInteger copyrightId) {
        if (copyrightId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "版权ID不能为空");
        }
        
        // 从服务层获取版权信息
        CopyrightInfo copyrightInfo = copyrightService.getCopyrightFromDB(copyrightId);
        
        return ResultUtils.success(copyrightInfo);
    }

    /**
     * 获取用户拥有的所有版权
     * @param address 用户地址
     * @return 版权列表
     */
    @GetMapping("/user/{address}")
    public BaseResponse<List<CopyrightInfo>> getCopyrightsByOwner(@PathVariable String address) {
        if (address == null || address.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户地址不能为空");
        }
        
        // 从服务层获取用户版权列表
        List<CopyrightInfo> copyrightInfos = copyrightService.getAllCopyrightsByOwner(address);
        
        return ResultUtils.success(copyrightInfos);
    }
    
    /**
     * 获取版权的转让历史记录
     * @param copyrightId 版权ID
     * @return 转让历史记录列表
     */
    @GetMapping("/{copyrightId}/transfers")
    public BaseResponse<List<CopyrightTransferInfo>> getTransferHistory(@PathVariable BigInteger copyrightId) {
        if (copyrightId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "版权ID不能为空");
        }
        
        // 获取转让历史并转换为Info对象
        List<CopyrightTransferInfo> result = copyrightService.getTransferHistoryInfo(copyrightId);
            
        return ResultUtils.success(result);
    }
    
    /**
     * 获取用户发起的转让记录
     * @param address 用户地址
     * @return 转让记录列表
     */
    @GetMapping("/transfers/from/{address}")
    public BaseResponse<List<CopyrightTransferInfo>> getTransfersFromUser(@PathVariable String address) {
        if (address == null || address.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户地址不能为空");
        }
        
        // 获取用户发起的转让记录
        List<CopyrightTransferInfo> result = copyrightService.getTransfersFromUserInfo(address);
            
        return ResultUtils.success(result);
    }
    
    /**
     * 获取用户接收的转让记录
     * @param address 用户地址
     * @return 转让记录列表
     */
    @GetMapping("/transfers/to/{address}")
    public BaseResponse<List<CopyrightTransferInfo>> getTransfersToUser(@PathVariable String address) {
        if (address == null || address.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户地址不能为空");
        }
        
        // 获取用户接收的转让记录
        List<CopyrightTransferInfo> result = copyrightService.getTransfersToUserInfo(address);
            
        return ResultUtils.success(result);
    }
    
    /**
     * 验证图片版权
     * @param file 图片文件
     * @return 验证结果
     */
    @PostMapping("/verify")
    public BaseResponse<Map<String, Object>> verifyImageCopyright(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
        
        try {
            // 调用服务层验证图片版权
            Map<String, Object> verificationResult = copyrightService.verifyImageCopyright(file);
            return ResultUtils.success(verificationResult);
        } catch (Exception e) {
            log.error("验证图片版权失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "验证图片版权失败：" + e.getMessage());
        }
    }
    
    /**
     * 通过哈希验证版权
     * @param imageHash 图片哈希
     * @return 验证结果
     */
    @GetMapping("/verify/{imageHash}")
    public BaseResponse<Map<String, Object>> verifyByHash(@PathVariable String imageHash) {
        if (imageHash == null || imageHash.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片哈希不能为空");
        }
        
        // 调用服务层通过哈希验证版权
        Map<String, Object> verificationResult = copyrightService.verifyByHash(imageHash);
        
        return ResultUtils.success(verificationResult);
    }

    /**
     * 从区块链获取指定地址的所有版权信息
     */
    @GetMapping("/chain/owner/{address}")
    public BaseResponse<List<CopyrightInfo>> getCopyrightsFromChain(@PathVariable String address) {
        try {
            List<CopyrightInfo> copyrights = copyrightService.getAllCopyrightsFromChain(address);
            return ResultUtils.success(copyrights);
        } catch (Exception e) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, e.getMessage());
        }
    }
} 